package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
)

// 获取扣款记录信息
func GetPapPayApplyRecordInfo(p map[string]interface{}) *models.PapPayApplyRecord {
	o := orm.NewOrm()
	papPayApplyRecord := &models.PapPayApplyRecord{}
	qs := o.QueryTable("PapPayApplyRecord")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["sn"]; ok {
		qs = qs.Filter("sn", p["sn"])
	}
	qs.One(papPayApplyRecord)
	return papPayApplyRecord
}

// 添加扣款记录信息
func AddPapPayApplyRecord(input url.Values) (int64, error) {
	o := orm.NewOrm()
	papPayApplyRecord := &models.PapPayApplyRecord{}
	user := &models.User{}
	if _, ok := input["user_id"]; ok {
		user.Id = utils.Atoi64(input["user_id"][0])
		o.Read(user)
	}
	papPayApplyRecord.User = user
	if _, ok := input["sn"]; ok {
		papPayApplyRecord.Sn = input["sn"][0]
	} else {
		papPayApplyRecord.Sn = GetPapPayApplySn()
	}
	if _, ok := input["amount"]; ok {
		papPayApplyRecord.Amount = utils.Atof64(input["amount"][0])
	}
	if _, ok := input["status"]; ok {
		papPayApplyRecord.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(papPayApplyRecord)
}

func GetPapPayApplySn() string {
	sn := utils.GetSn()
	p := map[string]interface{}{}
	p["sn"] = sn
	record := GetPapPayApplyRecordInfo(p)
	for record.Id > 0 {
		sn = utils.GetSn()
		p["sn"] = sn
		record = GetPapPayApplyRecordInfo(p)
	}
	return sn
}

// 修改扣款记录信息
func EditPapPayApplyRecord(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("PapPayApplyRecord").Filter("id", input["id"][0]).Update(p)
}

// 获取扣款记录列表
func GetPapPayApplyRecordList(p map[string]interface{}) (int64, []*models.PapPayApplyRecord) {
	var papPayApplyRecordList []*models.PapPayApplyRecord
	o := orm.NewOrm()
	qs := o.QueryTable("PapPayApplyRecord")
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&papPayApplyRecordList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, papPayApplyRecord := range papPayApplyRecordList {
			papPayApplyRecord.CreatedShow = papPayApplyRecord.Created.Format("2006-01-02 15:04:05")
			papPayApplyRecord.StatusShow = models.PapPayApplyStatus[papPayApplyRecord.Status]
		}
	}
	return totalCount, papPayApplyRecordList
}